#!/usr/bin/env python
from configobj import ConfigObj
import time
import threading
import socket
import pickle
from DTOSurvey import *
from Sms import *

MAX = 4096

class Loadbalancer:
    def __init__(self):
	config = ConfigObj("config")
	self._loadbalancerPort = int(config['loadbalancer']['port'])
    def waitForConnection(self):
	print "Loadbalancer: waiting for connection"
	serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
	serversocket.bind( ("localhost", self._loadbalancerPort) )
	serversocket.listen(1)
        sock, addr = serversocket.accept()
	print "Loadbalancer: accepted connection from module" 
	sock.setblocking(0)
	self._socket = sock
	""""""
	time.sleep(5)
    def sendToModule(self, dtoSurvey): 
	#print "Loadbalancer: sending to module [%s]" %dtoSurvey
	while dtoSurvey.hasNext():
	    try: 
		sms = dtoSurvey.getSms();
		print "sending to [%s]" %sms.getNumber(), "...", 
		self._socket.send(pickle.dumps(sms)) #### important
		print "sent"
		time.sleep(10)
		#self._socket.send(dtoSurvey.getSms())
	    except Exception, e:
		print "\n[E] Loadbalancer: could not send sms"
		print "[E]\tcause: ", e
		pass
    def recvFromModule(self):
	try: 
	    data = self._socket.recv(MAX)
	    print "Loadbalancer: recived from module [%s]" %pickle.loads(data)
	    return data
	except Exception, e:
	    #print "recv:no data"
	    return None

